﻿using SqlSugarRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FriendStar.Data.DBContext
{
   public class SugarDbContext
    {
        //禁止实例化
        private SugarDbContext()
        {

        }

        /// <summary>
        /// 数据库连接字符串
        /// </summary>
        public static string ConnectionString
        {
            get
            {
                string SqlConnString;
                //oracle
                //SqlConnString = "Data Source=hyf\\hyf;Initial Catalog=FriendStarBase;User ID=sa;Password=#hyf123";

                //oracle
                //SqlConnString = "Password=0;User ID=EPC;Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.0.11)(PORT=1521)))(CONNECT_DATA=(SERVER=orcl)(SERVICE_NAME=orcl)));";
                //通过配置文件获取  这里也可以动态根据cookies或session实现多库切换
                SqlConnString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
                return SqlConnString;
            }
        }
        /// <summary>
        /// 获取数据库实例
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static ISqlSugarClient GetInstance()
        {
            ISqlSugarClient db = null;
            //这里设置为sqlserver数据库 可根据实际使用进行调整
            //sqlserver
            //db = DbRepository.GetInstance(DbType.SqlServer, ConnectionString);
            //oracle
            db = DbRepository.GetInstance(DbType.SqlServer, ConnectionString, true);
            db.IsIgnoreErrorColumns = true;//忽略非数据库列
            db.IsEnableAttributeMapping = true;//启用属性映射
            db.IsEnableLogEvent = true;//启用日志事件
            db.LogEventStarting = PrintSql;
            return db;
        }


        /// <summary>
        /// 打印Sql
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="pars"></param>
        private static void PrintSql(string sql, string pars)
        {
            Console.WriteLine("sql:" + sql);
            if (pars != null)
            {
                Console.WriteLine(" pars:" + pars);
            }
            Console.WriteLine("");
        }
    }
}
